from info import constants
from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_blue
from flask import render_template, current_app, session, jsonify, request

"""
首页-点击排行榜接口
URL:/news_list
请求方式：GET
参数：cid（文章类别）、page（页码）、per_page（每页条数）可不传
"""


@index_blue.route('/news_list')
def get_news_list():
	# 1.获取参数
	cid = request.args.get('cid', '1')
	page = request.args.get('page', '1')
	per_page = request.args.get('per_page', constants.HOME_PAGE_MAX_NEWS)

	# 2.校验参数
	try:
		cid = int(cid)
		page = int(page)
		per_page = int(per_page)
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.PARAMERR, errmsg='参数传入错误')

	# 3.查询新闻数据
	filters = [News.status == 0]
	if cid != 1:
		filters.append(News.category_id == cid)

	try:
		paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.DBERR, errmsg='查询失败')

	# 获取查询后的数据
	news_model_list = paginate.items

	# 获取分页总页码
	total_page = paginate.pages

	# 获取当前页码
	current_page = paginate.page

	news_dict_li = []
	for news in news_model_list:
		news_dict_li.append(news.to_basic_dict())

	data = {
		'news_dict_li': news_dict_li,
		'total_page': total_page,
		'current_page': current_page
	}
	return jsonify(errno=RET.OK, errmsg='成功', data=data)


@index_blue.route('/')
def index():
	# 一、用户信息数据
	# 1.获取session信息
	user_id = session.get('user_id', None)
	user = None

	# 2.数据库中查询该id的用户信息
	try:
		user = User.query.get(user_id)
	except Exception as e:
		current_app.logger.error(e)

	# 二、首页点击排行数据
	# 获取数据数据库中数据
	news_list = []
	try:
		news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
	except Exception as e:
		current_app.logger.error(e)

	news_dict_li = []
	for news in news_list:
		news_dict_li.append(news.to_basic_dict())

	# 三、首页分类数据
	# 数据库查询
	try:
		categories = Category.query.all()
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.DBERR, errmsg='查询数据库失败')

	category_dict_li = []
	for category in categories:
		category_dict_li.append(category.to_dict())

	data = {
		'user': user.to_dict() if user else None,
		'news_dict_li': news_dict_li,
		'category_dict_li': category_dict_li
	}

	return render_template('news/index.html', data=data)


@index_blue.route('/favicon.ico')
def favicon():
	return current_app.send_static_file('news/favicon.ico')
